{% load static %}
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>管理系统</title>
  <link rel="stylesheet" href="{% static 'layui/css/layui.css' %}">
</head>
<body>

<form class="layui-form" style="margin-bottom: 20px;margin-top: 20px">
    <div class="layui-form-item">
        <label class="layui-form-label" style="width: 100px">请输入类型</label>
        <div class="layui-input-inline">
            <input type="text" name="title" value="" placeholder="请输入类型" class="layui-input" lay-affix="clear">
        </div>

<!--        <label class="layui-form-label" style="width: 100px">请选择类型</label>-->
<!--        <div class="layui-input-inline">-->
<!--            <div id="bId"  class="xm-select-demo"></div>-->
<!--        </div>-->

        <button class="layui-btn" lay-submit lay-filter="search">搜索</button>
        <button type="reset" id="reset" class="layui-btn layui-btn-primary" lay-filter="reset">清空</button>

    </div>

</form>

<div class="layui" style="margin:20px">
  {% csrf_token %}
  <table class="layui-hide" id="code" lay-filter="code"></table>
</div>

<script src="{% static 'layui/layui.js' %}"></script>
<script src="{% static 'js/xm-select.js' %}"></script>

<script>


  layui.use(['form','table','layer','jquery'],function (){
    let table = layui.table;
    let layer = layui.layer;
    let form = layui.form;
    let $ = layui.jquery;
    const BaseUrl = "{{BaseUrl}}"
    const typeArray = [
            {% for item in TypeQueryset %}
                { value: {{ item.id }}, name: "{{ item.title }}" }{% if not forloop.last %},{% endif %}
            {% endfor %}
        ];

    //搜索
     form.on('submit(search)', function(data){
        var field = data.field; // 获得表单字段
        console.log(field);
        // 执行搜索重载
        table.reload('code', {
          page: {
            curr: 1 // 重新从第 1 页开始
          },
          where: field // 搜索的字段
        });
        layer.msg('搜索成功',{icon: 1});
        return false; // 阻止默认 form 跳转
      });
    // });

    //xm-sleect下拉框
    let demo1 = xmSelect.render({
        el: '#bId',
        filterable: true,
        radio: true,
        name:"type",
        data: typeArray
    })

      $("#reset").click(function (){
          demo1.setValue([ ])
      })


    //头部工具栏事件
    table.on('toolbar(code)',function(obj){
      let event = obj.event
      if(event == 'add'){
         layer.open({
          title:'添加',
          type:2,
          content:'/sys/system/ny/code/type/add/',
          area:['500px','400px'],
          anim:1,  //弹层的出场动画
          end: function(){
              table.reloadData('code')
            }
        })
      }else if(event == 'batcDel'){
        //批量删除
        let id = obj.config.id;
        let checkStatus = table.checkStatus(id)
        let list = checkStatus.data
        if(list && list.length==0){
            layer.msg('没有选择要删除的数据');
        }else{
            layer.confirm('确定是否删除？',{icon: 3, title:'警告',btn:['确定','取消']},function(index){
                console.log(list);

                //构建参数
                let arr = [];
                for(let i=0;i<list.length;i++){
                    console.log(list)
                    arr.push(list[i].id)
                }

                //ajax调用
                $.ajax({
                    url:BaseUrl +'api/ny/code/batc-del/',
                    type:'DELETE',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-CSRFToken': '{{ csrf_token }}'
                        // 如果需要身份验证，可以在这里添加认证头
                        //'Authorization': 'Bearer your-token-if-needed'
                    },
                    data:JSON.stringify({"ids": arr}),

                    success: function(result) {
                        if(result.code===0){
                            layer.msg("删除成功:",{"icon":6})
                            table.reloadData('code')
                        }else{
                            layer.msg(result.msg)
                        }
                    },
                    error: function(xhr, status, error) {
                        layer.msg('您的操作有误！')
                        console.error("删除失败:", status, error);
                    }
                })

                //关闭弹出层
                layer.close(index);
            })
        }
      }else if(event == 'refresh'){
        layer.msg("刷新成功:",{"icon":6})
        table.reload('code')
      }else{
        layer.msg('您的操作有误！')
      }
    })


    //单元格事件处理
    table.on("tool(code)",function (obj){
      let event = obj.event
      if(event == 'del'){
        layer.confirm('确定删除?',{icon: 3, title:'警告',btn:['确定','取消']},function(index){
            //点击确定
            let id = obj.data.id;
            //AXAJ调用
            $.ajax({
                url:BaseUrl + 'api/ny/code/type/'+id+'/',
                type:'DELETE',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRFToken': '{{ csrf_token }}'
                    // 如果需要身份验证，可以在这里添加认证头
                    //'Authorization': 'Bearer your-token-if-needed'
                },
                success: function(result) {
                    if(result.code===0){
                        // console.log("删除成功:", result);
                        table.reloadData('code')
                        layer.msg("删除成功:",{"icon":6})
                    }else{
                        layer.msg(result.msg)
                    }
                },
                error: function(xhr, status, error) {
                    layer.msg('您的操作有误！')
                    console.error("删除失败:", status, error);
                }
            })
            //关闭弹出层
            layer.close(index);

        })
      }else if(event == 'edit'){
        console.log('执行编辑操作')
        layer.open({
          title:'编辑',
          type:2,
          content:'/sys/system/ny/code/type/edit/?id='+obj.data.id,
          area:['500px','400px'],
          anim:1,  //弹层的出场动画
          end: function(){
              table.reload('code')
            }
        })
      }else{
        layer.msg('您的操作有误！')
      }
    })

    // 展示表格已知数据
    table.render({
      elem:"#code",
      url: BaseUrl + "api/ny/code/type/",
      even:true,  //开启隔行背景
      defaultToolbar:[],
      toolbar:`
          <div>
<!--              <button type="button" lay-event="batcDel" class="layui-btn layui-btn-sm layui-bg-red">批量删除</button>-->
              <button type="button" lay-event="add" class="layui-btn layui-btn-sm layui-btn-normal">新增</button>
              <button type="button" lay-event="refresh" class="layui-btn layui-btn-sm"><i class="layui-icon layui-icon-refresh"></i> </button>
          </div>
      `,
      page: {
        limit:15,
        limits:[5,10,15,20]
      },
      request:{
        pageName:"page",
        limitName:"page_size"
      },
      parseData: function(res){
          console.log(res);
          return {
              "code": res.code, // 解析接口状态
              "msg": res.msg, // 解析提示文本
              "count": res.data.count, // 解析数据长度
              "data": res.data.results // 解析数据列表
            }
      },
      cols:[[
        // {type: 'checkbox', fixed: 'left'},
        {
            title:'编号',
            field:"id",
        },{
            title:'类型名称',
            field:"title",
        },{
            title:'备注',
            field:"remark",
        },{
            title:'最近更新时间',
            field:"utime",
        },{
            title:'操作',
            templet:function(d){
                let operate = `
                      <button type="button" lay-event='edit' class="layui-btn layui-btn-xs layui-btn-normal">修改</button>
                      <button type="button" lay-event='del' class="layui-btn layui-btn-xs layui-bg-red">删除</button>
                    `
                return operate;
            }
        },
      ]]
    })
  })
</script>

</body>
</html>